package com.car.datalayer.http;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map.Entry;

import com.car.comm.Logger;

public class CHttpRequest {
	/**
	 *  HTTP协议方法定义
	 */
	public static final int EHttpInvalid = 0;
	public static final int EHttpGet = 1;
	public static final int EHttpPost = 2;
	
	private int method;
	private String uri = "";
	private HashMap<String, String> headers;
	
	private byte[] postContent;

	public CHttpRequest(int method){
		this.method = method;
		headers = new HashMap<String, String>();
	}
	
	public int getMethod() {
		return method;
	}

	public void setMethod(int method) {
		this.method = method;
	}

	public String getUri() {
		return uri;
	}

	public void setUri(String uri) {
		this.uri = uri;
	}
	
	public byte[] getPostContent() {
		if(postContent == null){
			return new byte[0];
		}
		return postContent;
	}

	public void setPostContent(byte[] postContent) {
		this.postContent = postContent;
	}

	public HashMap<String, String> getHeaders() {
		return headers;
	}
	public void setHeader(String key, String value) {
		this.headers.put(key, value);
	}
	public String getHeader(String key){
		String value = this.headers.get(key);
		if(value == null){
			return "";
		}
		return value;
	}
	
	public String toString(){
		StringBuffer buffer = new StringBuffer(128);
		buffer.append("[\n");
		buffer.append("  method=" + this.method + "\n");
		buffer.append("  uri=" + this.uri + "\n");
		buffer.append("  headers={\n");
		for(Entry<String, String> entry : this.headers.entrySet()){
			buffer.append("    " + entry.getKey() + "=" + entry.getValue() + "\n");
		}
		buffer.append("  }\n");
		
		if(postContent != null){
			try {
				buffer.append(new String(postContent, "utf-8"));
			} catch (UnsupportedEncodingException e) {
				Logger.LogErr(e.getMessage());
			}
		}
		buffer.append("\n\n]\n");
		return buffer.toString();
	}
}
